<template>
    <div>
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            width="600px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            @close="closeDialog">
            
            <el-form
                ref="formRef"
                :model="formData"
                :rules="rules"
                label-width="100px"
                class="dict-form">
                
                <el-form-item label="字典名称" prop="name">
                    <el-input
                        v-model="formData.name"
                        placeholder="请输入字典名称"
                        maxlength="50"
                        show-word-limit
                        clearable>
                    </el-input>
                </el-form-item>
                
                <el-form-item label="字典编码" prop="code">
                    <el-input
                        v-model="formData.code"
                        placeholder="请输入字典编码（英文字母、数字、下划线）"
                        maxlength="50"
                        show-word-limit
                        clearable>
                    </el-input>
                </el-form-item>
                
                <el-form-item label="排序" prop="sort">
                    <el-input-number
                        v-model="formData.sort"
                        :min="0"
                        :max="9999"
                        controls-position="right"
                        style="width: 150px">
                    </el-input-number>
                </el-form-item>
                
                <el-form-item label="状态" prop="status">
                    <el-switch
                        v-model="formData.status"
                        active-text="启用"
                        inactive-text="禁用">
                    </el-switch>
                </el-form-item>
                
                <el-form-item label="备注">
                    <el-input
                        v-model="formData.description"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入备注信息"
                        maxlength="200"
                        show-word-limit>
                    </el-input>
                </el-form-item>
            </el-form>
            
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeDialog">关闭</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">
                        {{ mode === '新增' ? '保存' : '更新' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { apiDictCategoryAdd, apiDictCategoryEdit } from '@/api/api'

export default {
    name: 'AddCategory',
    
    data() {
        return {
            dialogVisible: false,
            dialogTitle: '',
            mode: '新增',
            loading: false,
            currentId: null,
            
            formData: {
                name: '',
                code: '',
                sort: 0,
                status: true,
                description: ''
            },
            
            rules: {
                name: [
                    { required: true, message: '请输入字典名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入字典编码', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
                    { 
                        pattern: /^[a-zA-Z0-9_]+$/, 
                        message: '编码只能包含英文字母、数字和下划线', 
                        trigger: 'blur' 
                    }
                ],
                sort: [
                    { required: true, message: '请输入排序', trigger: 'blur' },
                    { type: 'number', min: 0, max: 9999, message: '排序必须在0-9999之间', trigger: 'blur' }
                ]
            }
        }
    },
    
    methods: {
        // 打开弹窗
        open(data, mode) {
            this.dialogVisible = true
            this.mode = mode
            this.dialogTitle = mode + '字典分类'
            
            if (mode === '编辑' && data) {
                this.currentId = data.id
                this.formData = {
                    name: data.dict_name || data.name || '',
                    code: data.dict_code || data.code || '',
                    sort: data.sort_order !== undefined ? data.sort_order : (data.sort || 0),
                    status: data.is_active !== undefined ? data.is_active : (data.status !== undefined ? data.status : true),
                    description: data.remark || data.description || ''
                }
            } else {
                this.resetForm()
            }
        },
        
        // 关闭弹窗
        closeDialog() {
            this.dialogVisible = false
            this.resetForm()
        },
        
        // 重置表单
        resetForm() {
            this.currentId = null
            this.formData = {
                name: '',
                code: '',
                sort: 0,
                status: true,
                description: ''
            }
            
            if (this.$refs.formRef) {
                this.$refs.formRef.resetFields()
            }
        },
        
        // 提交表单
        submitForm() {
            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    this.loading = true
                    
                    // 转换字段名以匹配后端API
                    const apiData = {
                        dict_name: this.formData.name,
                        dict_code: this.formData.code,
                        sort_order: this.formData.sort,
                        is_active: this.formData.status,
                        remark: this.formData.description || ''
                    }
                    
                    const apiCall = this.mode === '新增' 
                        ? apiDictCategoryAdd(apiData)
                        : apiDictCategoryEdit(this.currentId, apiData)
                    
                    apiCall.then(res => {
                        this.loading = false
                        if (res.code === 200 || res.code === 201) {
                            this.$message.success(res.message || `${this.mode}字典分类成功`)
                            this.closeDialog()
                            this.$emit('refreshData')
                        } else {
                            this.$message.warning(res.message || `${this.mode}字典分类失败`)
                        }
                    }).catch(error => {
                        this.loading = false
                        this.$message.error(`${this.mode}字典分类失败: ${error.message || error}`)
                        console.error('API Error:', error)
                    })
                } else {
                    this.$message.warning('请检查表单信息')
                }
            })
        }
    }
}
</script>

<style scoped>
.dict-form {
    padding: 20px 0;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style> 